package org.yanghaokun.basic.controller;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.yanghaokun.basic.util.AjaxResult;
import org.yanghaokun.basic.util.FastDfsUtil;

/**
 * fastdfs接口控制器
 *    上传
 *    删除
 *    修改=删除+上传
 *    查询：http:8888
 */
@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {

    //@RequestPart文件上传
    //required=true 必传
    //value = "file"前端传过来的名称
    @PostMapping
    public AjaxResult upload(@RequestPart(required = true,value = "file") MultipartFile file) {
        try {
            String filename = file.getOriginalFilename();
            String extName = filename.substring(filename.indexOf(".") + 1);
            //上传
            String path = FastDfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(path);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("上传失败" + e.getMessage());
        }
    }

    @DeleteMapping
    public AjaxResult delete(@RequestParam(required = true,value = "path")String path) {
        try {
            //去掉路径开头的“/”
            String delBegin = path.substring(1);
            //获取groupname
            String groupName = delBegin.substring(0, delBegin.indexOf("/"));
            //获取之后的名字,也就是去掉了之前“/”之后的第一个“/”
            String pathName = delBegin.substring(delBegin.indexOf("/") + 1);
            //删除
            FastDfsUtil.delete(groupName,pathName);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("删除失败" + e.getMessage());
        }
    }
}
